<?php

namespace app\admin\controller;

use app\common\controller\Adminbase;
use think\Db;
use app\admin\model\Config as Config_Model;
use app\admin\model\SmsSetting;

class Sms extends Adminbase
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 短信配置
     * @param $name
     * @return mixed|null
     */
    public function index($name = 'alisms')
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['name'] = $name;
            if (!empty($data['template'])) {
                foreach ($data['template'] as $key => $val) {
                    if (empty($val['key']) || empty($val['value'])) {
                        unset($data['template'][$key]);
                    }
                }
                $data['template'] = json_encode(array_merge([], $data['template']));
            } else {
                $data['template'] = [];
            }
            $info = SmsSetting::where('name', $name)->find();
            if ($info) {
                $res = $info->allowField(true)->save($data);
            } else {
                $res = SmsSetting::create($data);
            }
            if ($res !== false) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        } else {
            $sms_config = Config_Model::where('name', 'sms_type')
                ->value('options');
            $type_arr = parse_attr($sms_config);
            $info = SmsSetting::where('name', $name)->find();
            if (empty($info)) {
                $data = [
                    'name' => $name,
                    'key' => '',
                    'secret' => '',
                    'sign' => '',
                    'app_url' => '',
                    'template' => [],
                    'appid' => '',
                ];
                SmsSetting::create($data);
                $info = $data;
            }
            $this->assign([
                'nameArray' => $type_arr,
                'info' => $info ?: [],
                'name' => $name,
            ]);
            return $this->fetch('sms/form');
        }
    }

}
